
package com.lmx.persistence.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.tmodel.Account;
import com.lmx.repoDomain.tmodel.DealFlow;
import com.lmx.repoDomain.tmodel.Dicttype;
import com.lmx.repoDomain.tmodel.PayRecord;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


/**
 * #{description}
 * 充值交易管理接口
 * @author shen
 * @version 1.00
 */
@Service
@Scope("prototype")
public class RechargeService<T>{
	
	private Log logger = LogFactory.getLog(this.getClass());

    @PersistenceContext
    private EntityManager em;
    
    @Autowired
    protected GenericService dslJpaService;
    
    @Autowired
    protected CommonService commonService;

    /**
     * 获取充值交易流水列表
     * @param values
     * @return
     */
    public List<Map<String ,Object>> getRechargeList(Map<String ,Object> values){
    	
		logger.debug("获取充值交易流水列表");
		
		List<Map<String ,Object>> rechargeList = new ArrayList<Map<String ,Object>>();
		
		String query = "select df from DealFlow df where df.businessType.id = 65 and df.delStatus != '1'";
		
		//用户名
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and df.payee.loginName like '%"+loginName+"%'";
		}
		//企业名称
		String entName = (String)values.get("entName");
		if(entName != null && !entName.isEmpty()){
			query = query + " and df.payee.entName like '%"+entName+"%'";
		}
		//姓名
		String name = (String)values.get("name");
		if(name != null && !name.isEmpty()){
			query = query + " and df.payee.name like '%"+name+"%'";
		}
		//充值日期
		String startTime = (String)values.get("startTime");
		String enTime = (String)values.get("enTime");
		if(startTime != null && !startTime.toString().isEmpty() && enTime != null && !enTime.toString().isEmpty()){
			try {
				Integer startInt = CommonUtil.strToIntegerTime(startTime);
				Integer endInt = CommonUtil.strToIntegerTime(enTime);
				query = query + " and df.tradeTime between "+startInt+" and "+endInt;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		query = query +" order by df.createTime desc";
		
		Query qu = this.em.createQuery(query);
		qu.setMaxResults((int)values.get("size"));
		qu.setFirstResult((int)values.get("pageNum"));
		List resultList = qu.getResultList();
		
		for(int i = 0 ; i < resultList.size() ; i ++){
			DealFlow dealFlow = (DealFlow) resultList.get(i);
			Map<String ,Object> dealFlowMap = new HashMap<String, Object>();
			
			Long delFlowID = dealFlow.getId();
			dealFlowMap.put("delFlowID", delFlowID.toString());
			
			String loginNameStr = "";
			String entNameStr = "";
			String nameStr = "";
			User user = dealFlow.getPayee();
			if(user != null){
				loginNameStr = user.getLoginName();
				entNameStr = user.getEntName();
				nameStr = user.getName();
			}
			dealFlowMap.put("loginName", loginNameStr==null?loginNameStr="":loginNameStr);//用户名
			dealFlowMap.put("entName", entNameStr==null?entNameStr="":entNameStr);//企业名称
			dealFlowMap.put("name", nameStr==null?nameStr="":nameStr);//真实姓名
			Double amount = dealFlow.getAmount();
			dealFlowMap.put("amount", amount==null?amount=0.0:amount);//充值金额
			Double payeeBalance = dealFlow.getPayeeBalance();
			dealFlowMap.put("payeeBalance", payeeBalance==null?payeeBalance=0.0:payeeBalance);//充值后余额
			String businessType = "";
			Dicttype dicttype = dealFlow.getBusinessType();
			if(dicttype != null){
				businessType = dicttype.getTypename();
			}
			dealFlowMap.put("businessType", businessType==null?businessType="":businessType);//交易类型
			String tradeTime = "";
			Integer tradeTimeInt = dealFlow.getTradeTime();
			if(tradeTimeInt != null){
				tradeTime = CommonUtil.integetTimeForString(tradeTimeInt);
			}
			dealFlowMap.put("tradeTime", tradeTime);//交易时间
			String createTime = "";
			Integer createTimeInt = dealFlow.getCreateTime();
			if(createTimeInt != null){
				createTime = CommonUtil.integetTimeForString(createTimeInt);
			}
			dealFlowMap.put("createTime", createTime);//创建时间
			String payRecordID = "";
			PayRecord payRecord = dealFlow.getPayRecord();
			if(payRecord != null){
				payRecordID = payRecord.getId().toString();
			}
			dealFlowMap.put("payRecordID", payRecordID);//支付记录id
			String remark = dealFlow.getRemark();
			dealFlowMap.put("remark", remark==null?remark="":remark);//支付记录id
			
			rechargeList.add(dealFlowMap);
		}
		
        return rechargeList;
    }
    
    /**
     * 获取充值交易流水列表总条数
     * @param values
     * @return
     */
    public int getRechargeListCount(Map<String ,Object> values){
    	
		logger.debug("获取充值交易流水列表总条数");
		
		String query = "select count(df.id) from DealFlow df where df.businessType.id = ?1 and df.delStatus != '1'";
		
		//用户名
		String loginName = (String)values.get("loginName");
		if(loginName != null && !loginName.isEmpty()){
			query = query + " and df.payee.loginName like '%"+loginName+"%'";
		}
		//企业名称
		String entName = (String)values.get("entName");
		if(entName != null && !entName.isEmpty()){
			query = query + " and df.payee.entName like '%"+entName+"%'";
		}
		//姓名
		String name = (String)values.get("name");
		if(name != null && !name.isEmpty()){
			query = query + " and df.payee.name like '%"+name+"%'";
		}
		//充值日期
		String startTime = (String)values.get("startTime");
		String enTime = (String)values.get("enTime");
		if(startTime != null && !startTime.toString().isEmpty() && enTime != null && !enTime.toString().isEmpty()){
			try {
				Integer startInt = CommonUtil.strToIntegerTime(startTime);
				Integer endInt = CommonUtil.strToIntegerTime(enTime);
				query = query + " and df.tradeTime between "+startInt+" and "+endInt;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Long businessTypeID = (long) 65;
		int count = (int)(long)this.em.createQuery(query)
				.setParameter(1, businessTypeID)
    			.getSingleResult();
		
        return count;
    }
    
    /**
     * 充值交易
     * @return
     */
    @Transactional
    public DealFlow addRecharge(DealFlow dealFlow){
    	logger.debug("充值交易");
    	//付款方 系统管理员
    	User payer = commonService.getSystemUser();
    	dealFlow.setPayer(payer);
    	//业务类型 充值
    	Dicttype businessType = new Dicttype();
    	businessType.setId((long) 65);
    	dealFlow.setBusinessType(businessType);
    	Integer tradeTime = CommonUtil.getCurrTimes(); //交易时间
    	dealFlow.setTradeTime(tradeTime);
    	Integer createTime = CommonUtil.getCurrTimes();//创建时间
    	dealFlow.setCreateTime(createTime);
    	//金额
    	Double amount = dealFlow.getAmount();
    	//收款方
    	User payee = dealFlow.getPayee();
    	//收款方账户信息
		List result = this.em.createQuery("select a from Account a where a.user.id = ?1")
				.setParameter(1, payee.getId())
				.getResultList();
		if(result.size()>0){
			Account account = (Account) result.get(0);
			Double balance = account.getBalance();//账户余额
			Double recharge = account.getRecharge();//总充值金额
			Long accountID = account.getId();
			if(balance == null){
				balance = 0.0;
			}
			if(recharge == null){
				recharge = 0.0;
			}
			recharge = amount+recharge;
			
			//收款方余额
	    	Double payeeBalance = amount+balance;
	    	dealFlow.setPayeeBalance(payeeBalance);
	    	
	    	//创建交易流水
			dslJpaService.setEntityClass(DealFlow.class);
			dealFlow = (DealFlow) dslJpaService.create(dealFlow);
			
			//更新收款方账户余额和总充值金额
			this.em.createQuery("update Account a set a.balance = ?1 , a.recharge = ?2 where a.id = ?3")
			.setParameter(1, payeeBalance)
			.setParameter(2, recharge)
			.setParameter(3, accountID)
			.executeUpdate();
		}
		return dealFlow;
    }
}
